const express = require("express");
const router = express.Router();
const { usersModel, codeModel } = require("../db/users");
const nodemailer = require("nodemailer");

const jwt = require("jsonwebtoken");
const secret = "your_jwt_secret";
// 生成验证码
function randomCode() {
  return Math.random().toString(36).slice(-4).toUpperCase();
}



// 登录发送验证码接口
router.post("/sendcode_login", async (req, res) => {
  const { phone, email } = req.body;
  const code = randomCode();
  console.log(phone, "phone");
  console.log(email, "email");
  if (phone) {
    const newCode = new codeModel({ phone, login_code: code, used: false });
    await newCode.save();
  } else if (email) {
    let transporter = nodemailer.createTransport({
      host: "smtp.qq.com", // 你的SMTP服务器
      port: 587,
      secure: false,
      auth: {
        user: "2717007649@qq.com", // 发件人邮箱
        pass: "bwrjpjenjtghdeeh", // 授权码
      },
    });
    let mailOptions = {
      from: '"你的昵称" <2717007649@qq.com>',
      to: email, // 收件人
      subject: "验证码", // 主题
      text: `你的验证码是：${code}`, // 内容
    };
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        return console.log(error);
      }
      console.log("Message sent: %s", info.messageId);
    });
  }
  const newCode = new codeModel({ email, login_code: code, used: false });
  await newCode.save();
  res.send({ code: 200, msg: `验证码已发送，请在10分钟内使用${code}` });
});

// 注册发送验证码接口
router.post("/sendcode", async (req, res) => {
  const { phone, email } = req.body;
  const code = randomCode();
  if (phone) {
    const newCode = new codeModel({ phone, code, used: false });
    await newCode.save();
  } else if (email) {
    const newCode = new codeModel({ email, code, used: false });
    await newCode.save();
  }
  let transporter = nodemailer.createTransport({
    host: "smtp.qq.com", // 你的SMTP服务器
    port: 587,
    secure: false,
    auth: {
      user: "2717007649@qq.com", // 发件人邮箱
      pass: "bwrjpjenjtghdeeh", // 授权码
    },
  });
  let mailOptions = {
    from: '"你的昵称" <2717007649@qq.com>',
    to: email, // 收件人
    subject: "验证码", // 主题
    text: `你的验证码是：${code}`, // 内容
  };
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return console.log(error);
    }
    console.log("Message sent: %s", info.messageId);
  });
  res.send({ code: 200, msg: `验证码已发送，请在10分钟内使用${code}` });
});

//注册接口
router.post("/createuser", async (req, res) => {
  const { phone, password, email, code, img } = req.body;
  if (email) {
    const codeDoc = await codeModel.findOne({ email, code, used: false });
    if (!codeDoc)
      return res.status(200).send({ code: 201, msg: "验证码错误或已失效" });
    codeDoc.used = true;
    await codeDoc.save();
    const user = await usersModel.findOne({ email });
    if (user) return res.status(200).send({ code: 201, msg: "用户已存在" });
    const newUser = new usersModel({ email, password, img });
    await newUser.save();
    res.send({ code: 200, msg: "注册成功" });
  } else {
    const codeDoc = await codeModel.findOne({ phone, code, used: false });
    console.log("找到的验证码文档:", codeDoc);
    if (!codeDoc)
      return res.status(200).send({ code: 201, msg: "验证码错误或已失效" });
    codeDoc.used = true;
    await codeDoc.save();
    const user = await usersModel.findOne({ phone });
    if (user) return res.status(200).send({ code: 201, msg: "用户已存在" });
    const newUser = new usersModel({ phone, password, img });
    await newUser.save();
    res.send({ code: 200, msg: "注册成功" });
  }
});

// 登录接口
router.post("/login", async (req, res) => {
  const { phone, password, email, code } = req.body;
  console.log("登录请求数据:", { phone, password, email, code });
  console.log("登录类型:", code ? "验证码登录" : "密码登录");
  if (phone) {
    if (code) {
      console.log("验证码登录 - 查找验证码:", { phone, code });
      const codeDoc = await codeModel.findOne({
        phone,
        used: false,
        login_code: code,
      });
      console.log("找到的验证码文档:", codeDoc);
      if (!codeDoc) {
        return res.status(200).send({ code: 201, msg: "验证码错误或已失效" });
      }
      codeDoc.used = true;
      await codeDoc.save();
      const user = await usersModel.findOne({ phone });
      if (!user) return res.status(200).send({ code: 201, msg: "用户不存在" });
      const accessToken = jwt.sign({ id: user._id }, secret, {
        expiresIn: "15m",
      });
      const refreshToken = jwt.sign({ id: user._id }, secret, {
        expiresIn: "7d",
      });
      res.cookie("refresh_token", refreshToken, {
        httpOnly: true,
        maxAge: 7 * 24 * 60 * 60 * 1000,
        // maxAge: 10 * 1000,
        sameSite: "lax",
      });
      res.send({ code: 200, accessToken, msg: "登录成功" });
    } else {
      console.log("密码登录 - 查找用户:", { phone, password });
      const user = await usersModel.findOne({ phone, password });
      console.log("找到的用户:", user);
      if (!user)
        return res.status(200).send({ code: 201, msg: "账号或密码错误" });
      const accessToken = jwt.sign({ id: user._id }, secret, {
        expiresIn: "15m",
      });
      const refreshToken = jwt.sign({ id: user._id }, secret, {
        expiresIn: "7d",
      });
      res.cookie("refresh_token", refreshToken, {
        httpOnly: true,
        maxAge: 7 * 24 * 60 * 60 * 1000,
        // maxAge: 10 * 1000,
        sameSite: "lax",
      });
      res.send({ code: 200, accessToken, msg: "登录成功" });
    }
  } else if (email) {
    if (code) {
      const codeDoc = await codeModel.findOne({
        email,
        used: false,
        login_code: code,
      });
      if (!codeDoc) {
        return res.status(200).send({ code: 201, msg: "验证码错误或已失效" });
      }
      codeDoc.used = true;
      await codeDoc.save();
      const user = await usersModel.findOne({ email });
      if (!user) return res.status(200).send({ code: 201, msg: "用户不存在" });
      const accessToken = jwt.sign({ id: user._id }, secret, {
        expiresIn: "15m",
      });
      const refreshToken = jwt.sign({ id: user._id }, secret, {
        expiresIn: "7d",
      });
      res.cookie("refresh_token", refreshToken, {
        httpOnly: true,
        maxAge: 7 * 24 * 60 * 60 * 1000,
        // maxAge: 10 * 1000,
        sameSite: "lax",
      });
      res.send({ code: 200, accessToken, msg: "登录成功" });
    }
  }
});

// 刷新token接口
router.post("/refresh-token", (req, res) => {
  const refreshToken = req.cookies["refresh_token"];
  if (!refreshToken) return res.status(401).send({ code: 401, msg: "未登录" });
  jwt.verify(refreshToken, secret, (err, decoded) => {
    if (err){
      return res.status(401).send({ code: 401, msg: "Refresh Token 失效" });
    }
    const accessToken = jwt.sign({ id: decoded.id }, secret, {
      expiresIn: "15m",
    });
    res.send({ code: 200, accessToken });
  });
});

// 选车数据接口 - 用于侧边栏悬停效果
router.get("/car-selection-data", async (req, res) => {
  try {
    // 模拟从数据库获取选车相关数据
    const carSelectionData = {
      categories: [
        {
          name: "热门车型",
          cars: [
            { name: "奔驰C级", price: "29.99万起", image: "https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=300&h=200&fit=crop" },
            { name: "宝马3系", price: "29.99万起", image: "https://images.unsplash.com/photo-1555215695-3004980ad54e?w=300&h=200&fit=crop" },
            { name: "奥迪A4L", price: "30.99万起", image: "https://images.unsplash.com/photo-1606664515524-ed2f786a0bd6?w=300&h=200&fit=crop" },
            { name: "特斯拉Model 3", price: "25.89万起", image: "https://images.unsplash.com/photo-1560958089-b8a1929cea89?w=300&h=200&fit=crop" }
          ]
        },
        {
          name: "新能源",
          cars: [
            { name: "比亚迪汉", price: "25.98万起", image: "https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=300&h=200&fit=crop" },
            { name: "蔚来ET7", price: "45.80万起", image: "https://images.unsplash.com/photo-1555215695-3004980ad54e?w=300&h=200&fit=crop" },
            { name: "小鹏P7", price: "28.99万起", image: "https://images.unsplash.com/photo-1606664515524-ed2f786a0bd6?w=300&h=200&fit=crop" },
            { name: "理想L9", price: "45.98万起", image: "https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=300&h=200&fit=crop" }
          ]
        },
        {
          name: "SUV",
          cars: [
            { name: "丰田汉兰达", price: "26.88万起", image: "https://images.unsplash.com/photo-1541899481282-d53bffe3c54d?w=300&h=200&fit=crop" },
            { name: "本田CR-V", price: "16.98万起", image: "https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=300&h=200&fit=crop" },
            { name: "大众途观L", price: "19.90万起", image: "https://images.unsplash.com/photo-1555215695-3004980ad54e?w=300&h=200&fit=crop" },
            { name: "哈弗H6", price: "9.89万起", image: "https://images.unsplash.com/photo-1606664515524-ed2f786a0bd6?w=300&h=200&fit=crop" }
          ]
        },
        {
          name: "轿车",
          cars: [
            { name: "丰田凯美瑞", price: "17.98万起", image: "https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=300&h=200&fit=crop" },
            { name: "本田雅阁", price: "16.98万起", image: "https://images.unsplash.com/photo-1541899481282-d53bffe3c54d?w=300&h=200&fit=crop" },
            { name: "日产天籁", price: "17.98万起", image: "https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=300&h=200&fit=crop" },
            { name: "大众帕萨特", price: "18.19万起", image: "https://images.unsplash.com/photo-1555215695-3004980ad54e?w=300&h=200&fit=crop" }
          ]
        }
      ],
      quickActions: [
        { name: "价格筛选", icon: "💰", description: "按价格区间筛选车型" },
        { name: "品牌筛选", icon: "🏷️", description: "按品牌筛选车型" },
        { name: "车型筛选", icon: "🚗", description: "按车型类别筛选" },
        { name: "对比功能", icon: "⚖️", description: "多车型对比分析" }
      ],
      recommendations: [
        { title: "本月热门", count: "2.3万人在选" },
        { title: "新能源推荐", count: "1.8万人在选" },
        { title: "性价比之选", count: "3.1万人在选" },
        { title: "豪华品牌", count: "1.2万人在选" }
      ]
    };

    res.json({
      code: 200,
      data: carSelectionData,
      msg: "获取选车数据成功"
    });
  } catch (error) {
    console.error("获取选车数据失败:", error);
    res.status(500).json({
      code: 500,
      msg: "获取选车数据失败",
      error: error.message
    });
  }
});

// 受保护API示例
router.get("/profile", (req, res) => {
  const auth = req.headers.authorization;
  if (!auth) return res.status(401).send({ code: 401, msg: "未登录" });
  const token = auth.split(" ")[1];
  jwt.verify(token, secret, (err, decoded) => {
    if (err)
      return res.status(401).send({ code: 401, msg: "Access Token 失效" });
    res.send({ code: 200, msg: "已登录", userId: decoded.id });
  });
});

module.exports = router;
